package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	a "godco/internal/model/auth"
	"godco/internal/svc"
	"godco/internal/types"
	"godco/internal/utils"
	"strings"
)

type OAuth2CallBackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOAuth2CallBackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OAuth2CallBackLogic {
	return &OAuth2CallBackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OAuth2CallBackLogic) OAuth2CallBack(req *types.CallBackReq) (resp *types.CallBackResp, err error) {
	// todo: add your logic here and delete this line
	l.Debugf("Code:%s", req.Code)
	l.Debugf("Install_id:%s", req.Install)
	l.Debugf("State:%s", req.State)
	l.Debugf("Email:%s", req.Email)

	//emailTemplateContent, _ := utils.ReadTemplateFile("sign_url_template.txt")
	//signUrl := l.svcCtx.Config.ApplicationConf.Host + l.svcCtx.Config.ApplicationConf.Home + "?aid=" + req.Install
	//emailContent := strings.Replace(emailTemplateContent, "{signUrl}", signUrl, -1)
	//
	//err = utils.SendEmail(l.svcCtx.Config.EConf.From, l.svcCtx.Config.EConf.Pwd, l.svcCtx.Config.EConf.Server, req.Email, "DCO签署地址", emailContent, "text/html")

	ret := types.CallBackResp{Code: 0, Message: "授权成功!"}
	TokenUrl := l.svcCtx.Config.ApplicationConf.AtomgitApi + "/login/oauth/access_token"
	// 使用code向AtomGit的令牌端点请求访问令牌
	tokenResp, err := utils.GetToken(TokenUrl, l.svcCtx.Config.Client.ClientID, l.svcCtx.Config.Client.ClientSecret, req.Code)
	if err != nil {
		l.Error(err)
		ret.Code = 400
		ret.Message = err.Error()
		return &ret, err
	}

	l.Debugf("Access Token: %s", tokenResp.AccessToken)
	l.Debugf("Refresh Token: %s", tokenResp.RefreshToken)
	// 获取用户个人信息
	info, err := utils.GetUserInfo(l.svcCtx.Config.ApplicationConf.AtomgitApi, tokenResp.AccessToken)
	if err == nil {
		l.Debugf("GetUserInfo ok,userID: %s", info.UID)
	} else {
		l.Error(err)
		ret.Code = 400
		ret.Message = err.Error()
		return &ret, err
	}
	// token入库
	data_, err := l.svcCtx.AuthModel.FindOneByInstallID(l.ctx, req.Install)
	if err == a.ErrNotFound {
		data := a.Auth{UID: info.UID, IID: req.Install, Name: info.Name, Login: info.Login, Email: info.Email, Phone: info.Phone, Token: tokenResp.AccessToken, TokenF: tokenResp.RefreshToken}
		//补全安装信息
		appInfo, err := utils.GetInstallationAppInfo(req.Install, l.svcCtx)
		if err == nil {
			data.TargetName = appInfo.Account.Login
			data.TargetId = appInfo.Account.Id
			data.TargetType = appInfo.Account.Type
		}
		err = l.svcCtx.AuthModel.Insert(l.ctx, &data)
		if err != nil {
			resp = &types.CallBackResp{
				Code:    403,
				Message: err.Error(),
			}
			return resp, nil
		}
		l.Debug("token入库成功")

		//发送邮件
		emailTemplateContent, _ := utils.ReadTemplateFile("sign_url_template.txt")
		signUrl := l.svcCtx.Config.ApplicationConf.Host + l.svcCtx.Config.ApplicationConf.Home + "?aid=" + req.Install
		emailContent := strings.Replace(emailTemplateContent, "{signUrl}", signUrl, -1)

		err = utils.SendEmail(l.svcCtx.Config.EConf.From, l.svcCtx.Config.EConf.Pwd, l.svcCtx.Config.EConf.Server, info.Email, "DCO签署地址", emailContent, "text/html")
	} else {
		data_.Token = tokenResp.AccessToken
		data_.TokenF = tokenResp.RefreshToken
		data_.UID = info.UID
		data_.Email = info.Email
		data_.Name = info.Name
		data_.Phone = info.Phone
		_, err = l.svcCtx.AuthModel.Update(l.ctx, data_)
		if err != nil {
			resp = &types.CallBackResp{
				Code:    403,
				Message: err.Error(),
			}
			return resp, nil
		}
		l.Debug("token更新成功")
	}

	return &ret, nil
}
